package cn.cubix.flow.controller;

import cn.cubix.flow.entity.WfUser;
import cn.cubix.flow.security.SecurityService;
import cn.cubix.flow.service.WfUserService;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
@RequestMapping("/api/security")
@RequiredArgsConstructor(onConstructor=@__({@Autowired,@Lazy}))
public class SecurityApi {

    private final AuthenticationManager authenticationManager;
    private final SecurityService securityService;
    private final WfUserService wfUserService;

    /**
     * 登录
     */
    @PostMapping("/signin")
    public Object signIn(@RequestBody JSONObject body, HttpServletResponse response){
        JSONObject result = new JSONObject();

        //用户验证 这其中将会用到 loadUserByUsername
        Authentication authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(body.getStr("username"), body.getStr("password")));
        //存储认证信息
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //生成token
        UserDetails userDetail = (UserDetails) authentication.getPrincipal();
        String token = securityService.generateToken(userDetail);

        // 放Cookie设置HttpOnly的话没法手动注销
//        Cookie cookie = new Cookie("token",token);
//        cookie.setHttpOnly(true);
//        cookie.setMaxAge(24*60*60);
//        cookie.setPath("/");
//        response.addCookie(cookie);

        return result.set("success",true)
                .set("token", token)
                .set("message","登录成功");
    }

    /**
     * 注册
     */
    @PostMapping("/signup")
    public Object signUp(@RequestBody JSONObject body){
        JSONObject result = new JSONObject().set("success",false).set("message","注册失败");

        String username = body.getStr("username");
        String password = body.getStr("password");

        if(wfUserService.count(new LambdaQueryWrapper<WfUser>().eq(WfUser::getUsername,username))==0){
            WfUser wfUser = new WfUser();
            wfUser.setUsername(username);
            wfUser.setPassword(securityService.encodePassword(password));
            wfUser.setPersonname(username);
            wfUserService.save(wfUser);
            result.set("success",true).set("message","注册成功");
        }else{
            result.set("message","注册失败，账号已被使用");
        }
        return result;
    }

    /**
     * 登出
     */
    @PostMapping("/signout")
    public Object signOut(@RequestBody JSONObject body){
        String username = body.getStr("username");

        return new JSONObject()
                .set("success",true)
                .set("message","登出成功");
    }

    /**
     * 账号信息
     */
    @GetMapping("/userinfo")
    public Object userInfo(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails)authentication.getPrincipal();
        WfUser wfUser = wfUserService.getOne(new LambdaQueryWrapper<WfUser>().eq(WfUser::getUsername,userDetails.getUsername()));
        wfUser.setPassword(null);
        return new JSONObject()
                .set("success",true)
                .set("message","获取用户信息成功")
                .set("userInfo",wfUser);
    }



}
